import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:myjd/api/ProductList.dart';
import 'package:myjd/api/index.dart';
import 'package:myjd/components/loading.dart';
import 'package:myjd/config/MyColors.dart';
import 'package:myjd/utils/ScreenAdaper.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class ProductListPage extends StatefulWidget {
  Map arguments;

  ProductListPage({Key key, this.arguments}) : super(key: key);

  _ProductListPage createState() => _ProductListPage();
}

class _ProductListPage extends State<ProductListPage> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  List products = [];
  int pageSize = 10;
  int page = 1;
  String sort = "";

/*二级导航数据*/
  List _subHeaderList = [
    {
      "id": 1,
      "title": "综合",
      "fileds": "all",
      "sort": -1,
    },
    {"id": 2, "title": "销量", "fileds": 'salecount', "sort": -1},
    {"id": 3, "title": "价格", "fileds": 'price', "sort": -1},
    {"id": 4, "title": "筛选"}
  ];

  //二级导航选中判断
  int _selectHeaderId = 1;

//  bool isEnd = false;

  @override
  void initState() {
    this.getList();
  }

  getList() async {
    Response result = await ProductListApi.getList(
        cid: this.widget.arguments["cid"], page: this.page, sort: this.sort);
    print("list");
    print(result);
    setState(() {
      this.products.addAll(result.data["result"]);
      this.page++;
    });
    return result.data["result"].length != this.pageSize;
  }

//
//  List<String> items = ["1", "2", "3", "4", "5", "6", "7", "8"]; //test
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  void _onRefresh() async {
    await Future.delayed(Duration(milliseconds: 1000));
    _refreshController.resetNoData();
    this.page = 1;
    this.products = [];
    await this.getList();
    // monitor network fetch

    // if failed,use refreshFailed()
//    setState(() {
////      this.items = ["1", "2", "3", "4", "5", "6", "7", "8"];
//      this.products = [];
//    });
    setState(() {});
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    await Future.delayed(Duration(milliseconds: 1000));
    // monitor network fetch
//    await Future.delayed(Duration(milliseconds: 1000));
//    // if failed,use loadFailed(),if no data return,use LoadNodata()
//    items.add((items.length + 1).toString());
    bool isEnd = await this.getList();
    if (mounted) setState(() {});
    if (isEnd) {
      _refreshController.loadNoData();
    } else {
      _refreshController.loadComplete();
    }
  }

  //
  Widget _productListWidget() {
    return Container(
        padding: EdgeInsets.all(10),
        margin: EdgeInsets.only(top: ScreenAdaper.height(80)),
        child: this.products.length == 0
            ? LoadingWidget()
            : SmartRefresher(
                enablePullDown: true,
                enablePullUp: true,
                header: WaterDropHeader(waterDropColor: MyColors.theme),
//                physics: ClampingScrollPhysics(),
//                footer: ClassicFooter(
//                  loadStyle: LoadStyle.ShowWhenLoading,
//                  completeDuration: Duration(milliseconds: 500),
//                ),
                footer: CustomFooter(
                  builder: (BuildContext context, LoadStatus mode) {
                    Widget body;
                    if (mode == LoadStatus.idle) {
                      body = Text("上拉加载更多...");
                    } else if (mode == LoadStatus.loading) {
                      body = Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          CupertinoActivityIndicator(),
                          Container(
                            margin: EdgeInsets.only(left: 20),
                            child: Center(
                              child: Text("加载中..."),
                            ),
                          )
                        ],
                      );
                    } else if (mode == LoadStatus.failed) {
                      body = Text("网络异常，请重试...");
                    } else if (mode == LoadStatus.canLoading) {
                      body = Text("release to load more");
                    } else {
                      body = Text("我也是有底线的...");
                    }
                    return Container(
                      height: 55.0,
                      child: Center(child: body),
                    );
                  },
                ),
                controller: _refreshController,
                onRefresh: _onRefresh,
                onLoading: _onLoading,
                child:
//                ListView.builder(
//                  itemBuilder: (c, i) =>
//                      Card(child: Center(child: Text(items[i]))),
//                  itemExtent: 100.0,
//                  itemCount: items.length,
//                ),
                    ListView.builder(
                        physics: BouncingScrollPhysics(),
                        itemExtent: ScreenAdaper.height(200),
                        itemCount: this.products.length,
                        itemBuilder: (context, index) {
                          return Column(
                            children: <Widget>[
                              Row(
                                children: <Widget>[
                                  Container(
                                    width: ScreenAdaper.width(180),
                                    height: ScreenAdaper.height(180),
//                        color: Colors.red,
                                    child: AspectRatio(
                                      aspectRatio: 1 / 1,
                                      child: Image.network(
                                          ApiBase.baseURL +
                                              this
                                                  .products[index]["s_pic"]
                                                  .replaceAll("\\", "/"),
                                          fit: BoxFit.cover),
                                    ),
                                  ),
                                  Expanded(
                                    flex: 1,
                                    child: Container(
                                      margin: EdgeInsets.only(
                                          left: ScreenAdaper.width(10)),
                                      height: ScreenAdaper.height(180),
//                          color: Colors.red,
                                      child: Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: <Widget>[
                                          Text(this.products[index]["title"],
                                              maxLines: 2,
                                              overflow: TextOverflow.ellipsis),
                                          Row(
                                            children: <Widget>[
                                              Container(
                                                height: ScreenAdaper.height(36),
                                                margin:
                                                    EdgeInsets.only(right: 10),
                                                padding: EdgeInsets.fromLTRB(
                                                    10, 0, 10, 0),

                                                //注意 如果Container里面加上decoration属性，这个时候color属性必须得放在BoxDecoration
                                                decoration: BoxDecoration(
                                                  borderRadius:
                                                      BorderRadius.circular(10),
                                                  color: Color.fromRGBO(
                                                      230, 230, 230, 0.9),
                                                ),

                                                child: Center(
                                                  child: Text("4g"),
                                                ),
                                              ),
                                              Container(
                                                height: ScreenAdaper.height(36),
                                                margin:
                                                    EdgeInsets.only(right: 10),
                                                padding: EdgeInsets.fromLTRB(
                                                    10, 0, 10, 0),
                                                decoration: BoxDecoration(
                                                  borderRadius:
                                                      BorderRadius.circular(10),
                                                  color: Color.fromRGBO(
                                                      230, 230, 230, 0.9),
                                                ),
                                                child: Center(
                                                  child: Text("100"),
                                                ),
                                              ),
                                            ],
                                          ),
                                          Text(
                                            "¥${this.products[index]["price"]}",
                                            style: TextStyle(
                                                color: Colors.red,
                                                fontSize: 16),
                                          )
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              Divider(height: ScreenAdaper.height(20))
                            ],
                          );
                        }),
              ));
  }

  //导航改变的时候触发
  _subHeaderChange(id) {
    if (id == 4) {
      _scaffoldKey.currentState.openEndDrawer();
      setState(() {
        this._selectHeaderId = id;
      });
    } else {
      setState(() {
        _refreshController.resetNoData();
        this._selectHeaderId = id;
        this.sort =
            "${this._subHeaderList[id - 1]["fileds"]}_${this._subHeaderList[id - 1]["sort"]}";

        //重置分页
        this.page = 1;
        //重置数据
        this.products = [];
        //改变sort排序
        this._subHeaderList[id - 1]['sort'] =
            this._subHeaderList[id - 1]['sort'] * -1;
        //回到顶部
//        _scrollController.jumpTo(0);
        //重置_hasMore
//        this._hasMore = true;
        //重新请求
//        this._getProductListData();
        this.getList();
      });
    }
  }

  Widget _showIcon(id) {
    if (id == 2 || id == 3) {
      if (this._subHeaderList[id - 1]["sort"] == 1) {
        return Icon(Icons.arrow_drop_down);
      }
      return Icon(Icons.arrow_drop_up);
    }
    return Text("");
  }

  Widget _subHeaderWidget() {
    return Positioned(
      top: 0,
      height: ScreenAdaper.height(80),
      width: ScreenAdaper.width(750), //不能给无限大
      child: Container(
//        width: ScreenAdaper.width(750),//可以不设置
//        height: ScreenAdaper.height(80),//可以不设置
          decoration: BoxDecoration(
              border: Border(
                  bottom: BorderSide(
                      width: 1, color: Color.fromRGBO(233, 233, 233, 0.9)))),
//          color: Colors.green,
          child: Row(
              children: this._subHeaderList.map((ele) {
            return Expanded(
              flex: 1,
              child: InkWell(
                child: Padding(
                    padding: EdgeInsets.fromLTRB(
                        0, ScreenAdaper.height(16), 0, ScreenAdaper.height(16)),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Text(
                          ele["title"],
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              color: (this._selectHeaderId == ele["id"])
                                  ? Colors.red
                                  : Colors.black54),
                        ),
                        _showIcon(ele["id"])
                      ],
                    )),
                onTap: () {
                  this._subHeaderChange(ele["id"]);
                },
              ),
            );
          }).toList()

//              Expanded(
//                flex: 1,
//                child: InkWell(
//                  child: Padding(
//                    padding: EdgeInsets.fromLTRB(
//                        0, ScreenAdaper.height(16), 0, ScreenAdaper.height(16)),
//                    child: Text("筛选", textAlign: TextAlign.center),
//                  ),
//                  onTap: () {
//                    _scaffoldKey.currentState.openEndDrawer();
//                  },
//                ),
//              ),

              )),
    );
  }

  @override
  Widget build(BuildContext context) {
    ScreenAdaper.init(context);
    return Scaffold(
        key: this._scaffoldKey,
        appBar: AppBar(
          title: Text("商品列表"),
          backgroundColor: MyColors.theme,
          centerTitle: true,
          actions: <Widget>[
            //去掉右侧抽屉的按钮
            Text("")
          ],
        ),
        endDrawer: Drawer(
          child: Container(
            child: Text("实现筛选功能"),
          ),
        ),
//      body: Text('商品列表${widget.arguments}'),
        body: Stack(
          children: <Widget>[
            this._productListWidget(),
            this._subHeaderWidget()
          ],
        ));
  }
}
